import type { Router, RouteLocationNormalized } from 'vue-router';
import { AxiosCanceler } from '/@/utils/http/axios/axiosCancel';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import { warn } from '/@/utils/log';
import settings from '@/config/settings';
import { PageEnum } from '@/enums/pageEnum';
import useUserStore from '@/store/modules/user';
import { createPermissionGuard } from '@/router/guard/permission';
import { ElMessage, ElNotification } from 'element-plus';

NProgress.configure({ showSpinner: false });
// Don't change the order of creation
export function setupRouterGuard(router: Router) {
  // createPageLoadingGuard(router);
  createHttpGuard(router);
  createScrollGuard(router);
  createMessageGuard(router);
  createProgressGuard(router);
  createPermissionGuard(router);
  createParamMenuGuard(router);
  createStateGuard(router);
}

function createStateGuard(router: Router) {
  router.afterEach((to) => {
    // Just enter the login page and clear the authentication information
    if (to.path === PageEnum.BASE_LOGIN) {
      const userStore = useUserStore();
      userStore.resetState();
    }
    return true;
  });
}

// TODO Used to handle page loading status
// function createPageLoadingGuard() {}

/**
 * The interface used to close the current page to complete the request when the route is switched
 * @param router
 */
function createHttpGuard(router: Router) {
  const { removeAllHttpPending } = settings;
  let axiosCanceler: Nullable<AxiosCanceler>;
  if (removeAllHttpPending) {
    axiosCanceler = new AxiosCanceler();
  }
  router.beforeEach(async () => {
    // Switching the route will delete the previous request
    axiosCanceler?.removeAllPending();
    return true;
  });
}

// Routing switch back to the top
function createScrollGuard(router: Router) {
  const isHash = (href: string) => {
    return /^#/.test(href);
  };

  const body = document.body;

  router.afterEach(async (to) => {
    // scroll top
    isHash((to as RouteLocationNormalized & { href: string })?.href) && body.scrollTo(0, 0);
    return true;
  });
}

/**
 * Used to close the message instance when the route is switched
 * @param router
 */
export function createMessageGuard(router: Router) {
  const { closeMessageOnSwitch } = settings;

  router.beforeEach(async () => {
    try {
      if (closeMessageOnSwitch) {
        ElMessage.closeAll();
        ElNotification.closeAll();
        // TODO
        // Modal.destroyAll();
      }
    } catch (error) {
      warn('message guard error:' + error);
    }
    return true;
  });
}

function createParamMenuGuard(router: Router) {
  router.beforeEach(async (to, _, next) => {
    // filter no name route
    if (!to.name) {
      next();
    } else {
      next();
    }
  });
}

export function createProgressGuard(router: Router) {
  router.beforeEach(async () => {
    NProgress.start();
    return true;
  });

  router.afterEach(async () => {
    NProgress.done();
    return true;
  });
}
